//
//  ZLRectExtension.swift
//  ZLExtension
//
//  Created by 赵振磊 on 2025/1/16.
//

import Foundation

public enum ZLCGRectRangeDirection {
    case top, left, bottom, right
}

public extension CGRect {
    var zl_x: CGFloat {
        get {
            self.minX
        }
        set {
            self.origin.x = newValue
        }
    }
    var zl_y: CGFloat {
        get {
            self.minY
        }
        set {
            self.origin.y = newValue
        }
    }
    var zl_maxX: CGFloat {
        get {
            self.maxX
        }
        set {
            self.zl_x = newValue - self.zl_width
        }
    }
    var zl_maxY: CGFloat {
        get {
            self.maxY
        }
        set {
            self.zl_y = newValue - self.zl_height
        }
    }
    var zl_width: CGFloat {
        get {
            self.width
        }
        set {
            self.size.width = newValue
        }
    }
    var zl_height: CGFloat {
        get {
            self.height
        }
        set {
            self.size.height = newValue
        }
    }
    var zl_center: CGPoint {
        get {
            CGPoint(x: self.midX, y: self.midY)
        }
        set {
            self.origin.x = newValue.x - self.width / 2.0
            self.origin.y = newValue.y - self.height / 2.0
        }
    }
    mutating func zl_offset(offset: CGPoint) {
        self.origin.x += offset.x
        self.origin.y += offset.y
    }
    mutating func zl_offset(offset: CGPoint, range: CGRect = .zero) {
        self.origin.x += offset.x
        self.origin.y += offset.y
        if range == .zero {
            return
        }
        if self.zl_y > range.zl_y {
            self.zl_y = range.zl_y
        }
        if self.zl_x > range.zl_x {
            self.zl_x = range.zl_x
        }
        if self.zl_maxY < range.zl_maxY {
            self.zl_maxY = range.zl_maxY
        }
        if self.zl_maxX < range.zl_maxX {
            self.zl_maxX = range.zl_maxX
        }
    }
    mutating func zl_offset(offset: CGPoint, range: CGRect = .zero, rangeCall: @escaping (ZLCGRectRangeDirection) -> Void) {
        self.origin.x += offset.x
        self.origin.y += offset.y
        if range == .zero {
            return
        }
        if self.zl_y > range.zl_y {
            self.zl_y = range.zl_y
            rangeCall(.top)
        }
        if self.zl_x > range.zl_x {
            self.zl_x = range.zl_x
            rangeCall(.left)
        }
        if self.zl_maxY < range.zl_maxY {
            self.zl_maxY = range.zl_maxY
            rangeCall(.bottom)
        }
        if self.zl_maxX < range.zl_maxX {
            self.zl_maxX = range.zl_maxX
            rangeCall(.right)
        }
    }
    
    mutating func zl_offsetX(offset: CGFloat) {
        self.origin.x += offset
    }
    
    mutating func zl_offsetY(offset: CGFloat) {
        self.origin.y += offset
    }
}
